// 统一请求封装（H5与小程序通用）
const BASE_URL = '/dyapi'
const DEFAULT_TIMEOUT = 15000
const TOKEN_STORAGE_KEY = 'dy_token'

function getStoredToken() {
	try {
		return uni.getStorageSync(TOKEN_STORAGE_KEY) || ''
	} catch (e) {
		return ''
	}
}

function setStoredToken(token) {
	try {
		uni.setStorageSync(TOKEN_STORAGE_KEY, token || '')
	} catch (e) {}
}

function clearStoredToken() {
	try {
		uni.removeStorageSync(TOKEN_STORAGE_KEY)
	} catch (e) {}
}

function request(options = {}) {
	const {
		url = '',
		method = 'GET',
		data = {},
		headers = {},
		timeout = DEFAULT_TIMEOUT,
		hideToast = false,
	} = options

	return new Promise((resolve, reject) => {
		const token = getStoredToken()
		const finalHeaders = Object.assign({
			'Content-Type': 'application/json',
		}, headers)
		if (token) {
			finalHeaders['Authorization'] = `Bearer ${token}`
		}

		const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`

		uni.request({
			url: fullUrl,
			method,
			data,
			timeout,
			header: finalHeaders,
			success: (res) => {
				const { statusCode, data: resp } = res
				if (statusCode >= 200 && statusCode < 300) {
					resolve(resp)
				} else if (statusCode === 401) {
					clearStoredToken()
					if (!hideToast) {
						uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' })
					}
					reject({ code: statusCode, message: 'Unauthorized', data: resp })
				} else {
					if (!hideToast) {
						uni.showToast({ title: resp?.message || `请求失败(${statusCode})`, icon: 'none' })
					}
					reject({ code: statusCode, message: resp?.message || 'Request Error', data: resp })
				}
			},
			fail: (err) => {
				if (!hideToast) {
					uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
				}
				reject(err)
			}
		})
	})
}

function get(url, params = {}, options = {}) {
	return request({
		url,
		method: 'GET',
		data: params,
		...options
	})
}

function post(url, body = {}, options = {}) {
	return request({
		url,
		method: 'POST',
		data: body,
		...options
	})
}

function uploadFile(url, filePath, options = {}) {
	const {
		name = 'file',
		formData = {},
		headers = {},
		timeout = DEFAULT_TIMEOUT,
		hideToast = false,
		onProgress,
		onTaskReady
	} = options

	return new Promise((resolve, reject) => {
		if (!filePath) {
			const err = new Error('filePath is required')
			if (!hideToast) {
				uni.showToast({ title: '缺少文件路径', icon: 'none' })
			}
			reject(err)
			return
		}

		const token = getStoredToken()
		const finalHeaders = Object.assign({}, headers)
		if (token) {
			finalHeaders['Authorization'] = `Bearer ${token}`
		}

		const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`

		const task = uni.uploadFile({
			url: fullUrl,
			filePath,
			name,
			formData,
			timeout,
			header: finalHeaders,
			success: (res) => {
				const { statusCode } = res
				let resp = res.data
				try {
					resp = typeof resp === 'string' ? JSON.parse(resp) : resp
				} catch (err) {}

				if (statusCode >= 200 && statusCode < 300) {
					resolve(resp)
				} else {
					if (!hideToast) {
						uni.showToast({ title: resp?.message || `上传失败(${statusCode})`, icon: 'none' })
					}
					reject({ code: statusCode, message: resp?.message || 'Upload Error', data: resp })
				}
			},
			fail: (err) => {
				if (!hideToast) {
					uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
				}
				reject(err)
			}
		})

		if (typeof onTaskReady === 'function') {
			onTaskReady(task)
		}

		if (task && typeof onProgress === 'function' && typeof task.onProgressUpdate === 'function') {
			task.onProgressUpdate((progressEvent) => {
				onProgress(progressEvent)
			})
		}
	})
}

export default {
	request,
	get,
	post,
	getStoredToken,
	setStoredToken,
	clearStoredToken,
	uploadFile
}


